package com.hmjk.health.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

public class ADInfo {
	private final String TAG = ADInfo.class.getSimpleName();
	
	private boolean isClean = true;
	
	private HealthApp mApp = null;
	private String keySetting = null;
	private String imageMark = null;
	private String imgLink = null;
	private String clickLink = null;
	private Bitmap bitmap = null;
	
	private void logd(String info){
		//Log.d(TAG, info);
	}
	
	

	public ADInfo(String jsonstr, String strKey, HealthApp app) throws JSONException{
		mApp = app;
		keySetting = strKey;
		if(jsonstr == null){
			isClean = true;
		}else{
			JSONObject json = new JSONObject(jsonstr);
			imageMark = json.getString("imagemark");
			imgLink = json.getString("imagelink");
			clickLink = json.getString("clicklink");
			isClean = false;	
		}
		mApp.ADDebug("create ADInfo, isClean=" + isClean + ", keySetting=" + keySetting);
	}
	
	public void setADInfo(String jsonstr, String strKey) throws JSONException{

		mApp.ADDebug("setADInfo:");
		
		if(jsonstr == null){
			imageMark = null;
			imgLink = null;
			clickLink = null;
			isClean = true;
			mApp.ADDebug("clear");
			return;
		}
		
		JSONObject json = new JSONObject(jsonstr);
		imageMark = json.getString("imagemark");
		imgLink = json.getString("imagelink");
		clickLink = json.getString("clicklink");
		keySetting = strKey;
		isClean = false;
		
		mApp.ADDebug("imageMark:" + imageMark);
		mApp.ADDebug("imgLink:" + imgLink);
		mApp.ADDebug("clickLink:" + clickLink);
		mApp.ADDebug("keySetting:" + keySetting);
		mApp.ADDebug("isClean:" + isClean);
	}
	
	public boolean isClean(){
		return isClean;
	}
		
	public void release(){

		synchronized(this){
			mApp.ADDebug("release:des="+imageMark+",bitmap="+bitmap);
			if(bitmap != null){
				if(bitmap.isRecycled() == false){
					bitmap.recycle();
					System.gc();
					logd("release:recycle");
				}
			}
			bitmap = null;
		}
	}
	
	public void showDescription(TextView v){
		synchronized(this){
			if(v != null){
				if(imageMark != null)
					v.setText(imageMark);
				else
					v.setText("");
			}
		}
	}
	
	public boolean show(ImageView v){
		synchronized(this){
			if((v == null) || (isClean == true)){
				mApp.ADDebug("ADInfo.show FALSE! ImageView=" + v + "; isClean=" + isClean);
				return false;
			}
			
			if((v != null) && (bitmap != null) && (bitmap.isRecycled() == false)){
				mApp.ADDebug("ADInfo.show OK");
				v.setImageBitmap(bitmap);
				v.setScaleType(ScaleType.FIT_XY);
				return true;
			}else{
				if(bitmap == null)
					mApp.ADDebug("ADInfo.show FALSE! bitmap == null");
				else if(bitmap.isRecycled() == true)
					mApp.ADDebug("ADInfo.show FALSE! bitmap isRecycled");
				else
					mApp.ADDebug("ADInfo.show FALSE! else...");
			}
		}
		return false;
	}
	
	private Runnable mLoadADRunnable = null;
	
	public void loadBitmap(final boolean forceLocal){
			
		if(mLoadADRunnable != null){
			mApp.ADDebug("AD loading now");
			return;
		}

		mLoadADRunnable = new Runnable() {
			
			@Override
			public void run() {
				synchronized(this){
					
					mApp.ADDebug("loadBitmap, forceLocal=" + forceLocal);
					String filepath = mApp.getADPath() + "/" + keySetting + ".jpg";
					File file = new File(filepath);
					if(bitmap != null){
						mApp.ADDebug("loadBitmap, bitmap is exist!");
					}else if(file.exists() || (forceLocal == true)){
						mApp.ADDebug("loadBitmap from local");
						if(file.exists() == false){
							mApp.ADDebug("loadBitmap, file is not exist!");
							return;
						}
						
						InputStream bmpIs = null;
						try{
							Uri imageUri = Uri.parse("file://" + filepath);
							bmpIs = mApp.getContentResolver().openInputStream(imageUri);
							if(bitmap != null){
								if(!bitmap.isRecycled()){
									bitmap.recycle();
									System.gc();
								}
							}
							bitmap = BitmapFactory.decodeStream(bmpIs);
							bmpIs.close();
							mApp.ADDebug("loadBitmap, load bitmap from file:" + imageUri);
						}catch(FileNotFoundException e){
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}else{
						mApp.ADDebug("loadBitmap from net");
						try {
							URL url = new URL(imgLink);
							
							if(url != null){
								HttpURLConnection con = (HttpURLConnection)url.openConnection();
								con.setConnectTimeout(3000);
								con.setRequestMethod("GET");
								con.setDoInput(true);
								int code = con.getResponseCode();
								if(code == 200){
								
										InputStream iStream = con.getInputStream();
										bitmap = BitmapFactory.decodeStream(iStream);
										boolean ok = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filepath));
										iStream.close();
										mApp.ADDebug("loadBitmap, save bitmap " + ok + ", file:" + filepath);
								}
							}
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}
				
				mLoadADRunnable = null;
			}
		};
		
		new Thread(mLoadADRunnable).start();
	
	}
	
	public String getUri(){
		return clickLink;
	}
}
